import { app, BrowserWindow, WebContents } from 'electron';
import { optimizer, platform } from '@electron-toolkit/utils';
import { createMainWindow, getMainWindow } from '$main/windows/main-window';
import { initialCommonWindowIPC, onCommonWindowEvent } from './window';
import { readProtocol } from '../registry';

export function bindInitEvent() {
  app.on('browser-window-created', (_, window) => {
    /**
     * 绑定快捷键：f12 打开或者关闭devtools
     * 关闭生产环境 CommandOrControl + R
     */
    optimizer.watchWindowShortcuts(window);
    onCommonWindowEvent(window);
    window.setMenu(null);
  });

  app.on('window-all-closed', () => {
    if (!platform.isMacOS) {
      app.quit();
    }
  });

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createMainWindow();
    }
  });

  app.on('before-quit', () => {
    //通知断开socket连接
  });

  app.on('second-instance', (_, argv) => {
    const mainWindow = getMainWindow();
    if (!mainWindow) return;

    if (!mainWindow?.isDestroyed()) {
      mainWindow?.restore();
      mainWindow?.focus();
      mainWindow?.unmaximize();
      mainWindow?.center();
      mainWindow?.show();
    }

    const customUrl = readProtocol(argv);
    if (customUrl)
      sendWebContentsEvent(mainWindow.webContents, 'rc:enter-protocol-data', customUrl);

    mainWindow.focus();
  });

  initialCommonWindowIPC();
}

//向客户端发送事件
export function sendWebContentsEvent(webContents: WebContents, channel: string, ...args: any) {
  webContents.send(channel, args);
}
